# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Maintainer: Ray Donnelly <mingw.android@gmail.com>

_realname=tesseract-ocr
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=5.3.2
pkgrel=2
pkgdesc="Tesseract OCR (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url="https://github.com/tesseract-ocr/tesseract"
license=("spdx:Apache-2.0")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc" "${MINGW_PACKAGE_PREFIX}-autotools")
depends=(${MINGW_PACKAGE_PREFIX}-asciidoc
         ${MINGW_PACKAGE_PREFIX}-cairo
         ${MINGW_PACKAGE_PREFIX}-curl
         ${MINGW_PACKAGE_PREFIX}-gcc-libs
         ${MINGW_PACKAGE_PREFIX}-omp
         ${MINGW_PACKAGE_PREFIX}-icu
         ${MINGW_PACKAGE_PREFIX}-leptonica
         ${MINGW_PACKAGE_PREFIX}-libarchive
         ${MINGW_PACKAGE_PREFIX}-pango
         ${MINGW_PACKAGE_PREFIX}-zlib)
source=(${_realname}-${pkgver}.tar.gz::https://github.com/tesseract-ocr/tesseract/archive/${pkgver}.tar.gz
        https://github.com/tesseract-ocr/tessdata_fast/raw/main/osd.traineddata
        0001-check-msys2-tessdata-location.patch)
sha256sums=('b99d30fed47360d7168c3e25d194a7416ceb1d9e4b232c7f121cc5f77084d3e7'
            '9cf5d576fcc47564f11265841e5ca839001e7e6f38ff7f7aacf46d15a96b00ff'
            'dfa396e9476a03fc8c24ba59394a5dee2c6a604cee44b9b957be4fda0b5e4392')

prepare() {
  cd "${srcdir}/tesseract-${pkgver}"
  patch -p1 -i ${srcdir}/0001-check-msys2-tessdata-location.patch
  ./autogen.sh
}

build() {
  [[ -d "${srcdir}/build-${MSYSTEM}" ]] && rm -rf "${srcdir}/build-${MSYSTEM}"
  cp -r "${srcdir}/tesseract-${pkgver}" "${srcdir}/build-${MSYSTEM}"
  cd "${srcdir}/build-${MSYSTEM}"

  local -a extra_config
  if check_option "debug" "y"; then
    extra_config+=( --enable-debug )
  fi

  if [[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]]; then
    LDFLAGS+=" -lomp"
  fi

  ./configure \
    --build=${MINGW_CHOST} \
    --host=${MINGW_CHOST} \
    --target=${MINGW_CHOST} \
    --prefix=${MINGW_PREFIX} \
    "${extra_config[@]}"

  make
  make training
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"
  ./tesseract --version
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"
  make DESTDIR="${pkgdir}" install
  make DESTDIR="${pkgdir}" training-install

  install -Dm644 ${srcdir}/osd.traineddata ${pkgdir}${MINGW_PREFIX}/share/tessdata/osd.traineddata

  # Fix .pc file
  sed -s "/^Libs:/ { s|$(cygpath -m ${MINGW_PREFIX})|${MINGW_PREFIX}|g }" -i "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/tesseract.pc
}
